﻿using System;
using System.IO;
using System.Web.Hosting;

using DreamCube.Foundation.Basic.Extensions.System;
using DreamCube.Foundation.Basic.Extensions.System.StringIO;

namespace WebServer.Service.BLL
{
    /// <summary>
    /// 网站程序域对象创建类
    /// </summary>
    public static class WebHostManager
    {
        #region "公共方法"

        /// <summary>
        /// 创建一个网站的程序域
        /// </summary>
        /// <returns></returns>
        public static WebHost CreateWebHost(String physicalPath, String virtualPath = "/")
        {
            CopyDependFileToTargetWeb(physicalPath);
            WebHost host = (WebHost)ApplicationHost.CreateApplicationHost(typeof(WebHost),
                                                    virtualPath,
                                                    physicalPath);
            return host;
        }
        
        #endregion

        #region "私有方法"
            
        /// <summary>
        /// 把服务器运行所依赖的dllcopy到网站的bin目录下
        /// </summary>
        private static void CopyDependFileToTargetWeb(String targetPath)
        {
            String directoryName = Path.Combine(targetPath, "bin");
            Directory.CreateDirectory(directoryName);
            String appBin = AppDomain.CurrentDomain.BaseDirectory;
            String[] files = null;
            appBin.GetFiles(out files, "*.dll");

            if (files != null)
            {
                for (Int32 i = 0; i < files.Length; i++)
                    File.Copy(files[i], files[i].Replace(files[i].LeftOfLast("\\"), directoryName), true);
            }
        }

        #endregion
    }
}
